package com.yby6.common.utils.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.*;

/**
 * @Author yang shuai
 * @Date 2022/9/3
 */
public class XmlUtil {

    /**
     * 简单解析xml
     *
     * @param in
     * @return
     */
    public static Map<String, Object> parseXML(InputStream in) {
        Map<String, Object> map = new HashMap<>();
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(in);
            Element root = document.getRootElement();
            Iterator iterator = root.elementIterator();
            while (iterator.hasNext()) {
                Element element = (Element) iterator.next();
                map.put(element.getName(), element.getStringValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * <p>Desc:weChat构建请求参数</p>
     * <p>参数名ASCII码从小到大排序（字典序)</p>
     *
     * @param params
     * @return
     */
    public static String buildBodyXml(Map<String, Object> params) {
        SortedMap<String, Object> sort = new TreeMap<String, Object>(params);
        Set<String> keySet = sort.keySet();
        StringBuilder sb = new StringBuilder("<xml>");
        for (Object key : keySet) {
            sb.append(String.format("<%s>%s</%s>", key, params.get(key), key));
        }
        sb.append("</xml>");
        return sb.toString();
    }

}